package com.anXin.mall.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.anXin.mall.config.AlipayConfig;
import com.anXin.mall.service.impl.BizAlipayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin    // @CrossOrigin注解 解决uniapp跨域访问后端问题。
@RequestMapping("/productOrder")
public class UniProductOrderController {
    @Autowired
    private AlipayConfig alipayConfig;
    @Autowired
    private BizAlipayService alipayService;

    /**
     * 发起支付
     *
     * @return
     */
    @GetMapping("/pay")
    public Object pay(Double price) {
        System.out.println("正在测试支付宝支付···");
        String s = alipayService.appPay("测试支付", String.valueOf(System.currentTimeMillis()), new BigDecimal(price).toString());
        System.out.println(s);
        return s;
    }
    /**
     * 订单回调
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/notify")
    public String orderNotify(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        try {
            boolean flag = AlipaySignature.rsaCheckV1(params, alipayConfig.getAlipayPublicKey(), alipayConfig.getCharset(), alipayConfig.getSignType());
            if (flag) {
                System.out.println("支付回调信息:"+ params);
                return "success";
            } else {
                return "error";
            }
        } catch (AlipayApiException e) {
            System.out.println("支付宝错误回调:"+e.getErrMsg());
            e.printStackTrace();
            return "error";
        }
    }
}
